<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery1">
        <a-row :gutter="24">
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="门店">
              <a-cascader
                :options="departModel.departTreeOptions"
                :showSearch="true"
                expand-trigger="hover"
                placeholder=""
                :fieldNames="departModel.fieldNames"
                style="width: 180px"
                v-model="queryParam.selecteddeparts"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="退货单号">
              <a-input placeholder="" v-model="queryParam.refundNo" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="退单时间">
              <a-range-picker
                :ranges="{ 今天: [moment(), moment()], 本月: [moment().startOf('month'), moment().endOf('month')] }"
                v-model="orderDateRange"
                @change="handleChange"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="SKU编码">
              <a-input placeholder="" v-model="queryParam.itemSku" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="关联订单号">
              <a-input placeholder="" v-model="queryParam.orderNo" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery1" icon="search">查询</a-button>
              <a-button type="default" @click="searchReset1" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls1('退货单')">导出</a-button>
      <a-button type="primary" icon="download" @click="handleExportDetailXls('退货单商品明细')">导出退货商品明细</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <span slot="refundBizStatusLabel" slot-scope="text, record">
          <a-tag color="orange" v-if="record.refundBizStatus === 'NEW'">{{ text }}</a-tag>
          <a-tag color="blue" v-if="record.refundBizStatus === 'REFUND_SUCC'">{{ text }}</a-tag>
          <a-tag color="default" v-if="record.refundBizStatus === 'CANCEL'">{{ text }}</a-tag>
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <posCashierOrder-modal ref="modalForm" @ok="modalFormOk"></posCashierOrder-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import moment from 'moment'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import PosCashierOrderModal from './modules/PosCashierOrderModal'
import { queryDepartTreeList1 } from '@/api/api'
import { getAction, downFile } from '@/api/manage'

export default {
  name: 'PosOrderRefundList',
  mixins: [JeecgListMixin],
  components: {
    PosCashierOrderModal,
  },
  data() {
    return {
      description: '退货单管理页面',
      departModel: {
        departTreeOptions: [],
        fieldNames: { label: 'title', value: 'value', children: 'children' },
      },
      orderDateRange: [],
      // 表头
      columns: [
        {
          title: '机构',
          align: 'center',
          dataIndex: 'orgName',
        },
        {
          title: '门店',
          align: 'center',
          dataIndex: 'shopName',
        },
        {
          title: '退货单号',
          align: 'center',
          dataIndex: 'refundNo',
        },
        {
          title: '关联收银单号',
          align: 'center',
          dataIndex: 'orderNo',
        },

        {
          title: '操作人',
          align: 'center',
          dataIndex: 'operUserName',
        },
        {
          title: '退货时间',
          align: 'center',
          dataIndex: 'refundTime',
        },
        {
          title: '退货商品数量',
          align: 'center',
          dataIndex: 'refundCnt',
        },
        {
          title: '退款金额(元)',
          align: 'center',
          dataIndex: 'refundAmount',
        },
        {
          title: '退货原因',
          align: 'center',
          dataIndex: 'refundReason',
        },
        {
          title: '退货状态',
          align: 'center',
          dataIndex: 'refundBizStatusLabel',
          scopedSlots: { customRender: 'refundBizStatusLabel' },
        },

        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/cashier/posOrderRefund/list',
        exportXlsUrl: 'cashier/posOrderRefund/exportXls',
        exportDetailXlsUrl: 'cashier/posOrderRefund/exportDetailXls',
      },
    }
  },
  computed: {},
  created() {
    this.loadDepartTree()
  },
  methods: {
    moment,
    handleChange(date, dateString) {
      this.queryParam.beginTime = dateString[0]
      this.queryParam.endTime = dateString[1]
    },
    searchReset1() {
      this.queryParam = {}
      this.orderDateRange = []
      this.loadData()
    },
    handleDetail(record) {
      this.$refs.modalForm.view(record.orderId, record.orgName)
      this.$refs.modalForm.title = '订单详情'
      this.$refs.modalForm.disableSubmit = false
    },
    searchQuery1() {
      this.assembleQueryParam()
      this.loadData()
    },
    assembleQueryParam() {
      console.log(this.queryParam.selecteddeparts)
      let selecteddeparts = this.queryParam.selecteddeparts
      if (selecteddeparts && selecteddeparts.length == 2) {
        this.queryParam.orgIds = selecteddeparts[0]
        this.queryParam.shopIds = selecteddeparts[1] == 0 ? null : selecteddeparts[1]
      } else {
        this.queryParam.orgIds = null
        this.queryParam.shopIds = null
      }
    },
    loadDepartTree() {
      queryDepartTreeList1().then((res) => {
        if (res.success) {
          let departList = res.result
          if (departList.length == 1 && departList[0].orgType == 1) {
            departList = departList[0].children
          }
          this.departModel.departTreeOptions = departList

          this.departModel.departTreeOptions.forEach((x) => {
            if (!x['children']) {
              x['children'] = []
            }
            let allShop = { title: '全部门店', value: '0' }
            x['children'].unshift(allShop)
          })
        }
      })
    },
    checkExportParam() {
      if (this.orderDateRange.length !== 2) {
        this.$message.warning('最多支持一个月跨度时间的数据导出')
        return false
      }

      let beginTime = this.orderDateRange[0]
      let endTime = this.orderDateRange[1]
      let diffDays = endTime.diff(beginTime, 'day')
      console.log('日期间隔天数', diffDays)
      if (diffDays > 31) {
        this.$message.warning('最多支持一个月跨度时间的数据导出')
        return false
      }

      return true
    },
    handleExportXls1(fileName) {
      if (!this.checkExportParam()) {
        return
      }
      this.handleExportXls(fileName)
    },
    handleExportDetailXls(fileName) {
      if (!this.checkExportParam()) {
        return
      }

      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportDetailXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>